package com.example.myproject;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.util.ArrayList;
import java.util.List;
/**
 * 新闻碎片
 */
public class NewsFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;   //标题
    private String mParam2;   //网址
    ListView lv;
    List<NewsBean.DataBean.FeedlistBean> feedlist;   //数据源
    private NewsBaseAdapter adapter;
    boolean isHaveHeader=false;//是否有头布局的标志位
    public NewsFragment() {}
    public static NewsFragment newInstance(String param1,String param2) {
        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_news, container, false);
        lv = view.findViewById(R.id.frag_lv);
        feedlist = new ArrayList<>();
        //设置适配器
        adapter = new NewsBaseAdapter(getContext(), feedlist);
        lv.setAdapter(adapter);
        connectNetwork(mParam2);
        setItemClick();
        return view;
    }
//   设置listview每一条的点击事件的方法
    private void setItemClick() {
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NewsBean.DataBean.FeedlistBean.ItemsBeanX beanX=null;
                if (isHaveHeader){
                    beanX=feedlist.get(position-1).getItems().get(0);
                }else {
                    beanX=feedlist.get(position).getItems().get(0);
                }
                String fileurl = beanX.getFileurl();   //二级页面的网址
                Intent intent = new Intent(getContext(), InfoActivity.class);
                intent.putExtra("url",fileurl);
                startActivity(intent);
            }
        });

    }

    private void connectNetwork(String url) {
//        1.构建请求参数
        RequestParams params = new RequestParams(url);
//        2.发起请求   发起请求之前要使用声明
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {  //请求成功时会调用的方法
                //1,解析数据  jsonobject、jsonarray / gson / fastjson
                NewsBean newsBean = new Gson().fromJson(result, NewsBean.class);
                NewsBean.DataBean data = newsBean.getData();
                List<NewsBean.DataBean.FeedlistBean> list = data.getFeedlist();  //显示的数据源
                //2.将获取到的数据添加到listview的数据源当中
                feedlist.addAll(list);
                //3.通知适配器更新数据
                adapter.notifyDataSetChanged();
                //得到轮播条对象
                NewsBean.DataBean.BannerBean banner = data.getBanner();
                if (banner.getCount()>0) {
                    //给listview添加banner头布局
                    isHaveHeader=true;
                    View headerView = getHeaderView(banner);
                    lv.addHeaderView(headerView);
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {  //请求失败时会调用的方法
                Log.i("animee", "onError: ex=="+ex.getMessage());
            }
            @Override
            public void onCancelled(CancelledException cex) {} // 请求被取消时会执行的方法
            @Override
            public void onFinished() { }  //请求完成时会调用的方法
        });
    }
     /*获取头布局的方法*/
    private View getHeaderView(NewsBean.DataBean.BannerBean banner) {
        View headerView = getLayoutInflater().inflate(R.layout.item_headerview,null);
        ViewPager headerVp = headerView.findViewById(R.id.header_vp);
        LinearLayout headerLayout = headerView.findViewById(R.id.header_layout);
        //给viewpager填充数据
        List<NewsBean.DataBean.BannerBean.ItemsBean> itemsList = banner.getItems();
        List<View>viewList = new ArrayList<>(); //viewpager的数据源
        List<ImageView>pointList=new ArrayList<>();//管理小点点的集合
        for (int i = 0; i < itemsList.size(); i++) {
            NewsBean.DataBean.BannerBean.ItemsBean itemsBean = itemsList.get(i); //得到指定位置的数据
            View view = getLayoutInflater().inflate(R.layout.item_vp,null);
            TextView tv = view.findViewById(R.id.item_vp_tv);
            ImageView iv = view.findViewById(R.id.item_vp_iv);
            tv.setText(itemsBean.getTitle());
            Picasso.with(getContext()).load(itemsBean.getImg()).into(iv);
            setVpItemClick(view,itemsBean);
            viewList.add(view);   //添加viewpager的数据源当中，统一管理
            //初始化每一个小点点
            ImageView pointView=new ImageView(getContext());
            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(0,0,8,0);
            pointView.setLayoutParams(params);
            pointView.setImageResource(R.mipmap.p1);
            headerLayout.addView(pointView);
            pointList.add(pointView);
        }
        pointList.get(0).setImageResource(R.mipmap.p2);
        setHeaderVpListener(pointList,headerVp);
        // 设置适配器
        HeaderPagerAdapter headerPagerAdapter=new HeaderPagerAdapter(getContext(),viewList);
        headerVp.setAdapter(headerPagerAdapter);
        return headerView;
    }

    private void setVpItemClick(View view, NewsBean.DataBean.BannerBean.ItemsBean itemsBean) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String fileurl=itemsBean.getFileurl();//传值网址
                Intent it=new Intent(getActivity(),InfoActivity.class);
                it.putExtra("url",fileurl);
                startActivity(it);
            }
        });
    }
//监听headerview当中的viewpager滑动到哪个页面
    private void setHeaderVpListener(List<ImageView> pointList, ViewPager headerVp) {
        headerVp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                for (int i=0;i<pointList.size();i++){
                    pointList.get(i).setImageResource(R.mipmap.p1);
                }
                pointList.get(position).setImageResource(R.mipmap.p2);
            }
        });
    }
    }


